package com.lzy.permission.dao;

import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.lzy.permission.entity.User;

/**
 * 唯一取得用户信息接口
 * @author pwz
 *
 */
public class HibernateDaoImpl extends HibernateDaoSupport implements UserDetailsService {

	public static final String DEF_USERS_BY_USERNAME_QUERY = "from User where username = ?";

	public HibernateDaoImpl() {
	}
	
	@SuppressWarnings( "unchecked" )
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		List<User> users = getHibernateTemplate().find(DEF_USERS_BY_USERNAME_QUERY, username );
		
		if (users.size() == 0) {
            logger.debug("Query returned no results for user '" + username + "'");

            throw new UsernameNotFoundException("Username {" + username +"} not found");
        }

        User user = users.get(0); // contains no GrantedAuthority[]

        return new UserDetailsHibernateImpl(user);
	}

}
